package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class DtsStorageServiceImpl implements DtsStorageService {
    @Autowired
    DtsStorageMapper storageMapper;


    @Override
    public IPage<DtsStorage> findByPage(Integer page, Integer limit, String sort, String order, String key, String name) {
        IPage<DtsStorage> iPage = new Page<>();
        QueryWrapper<DtsStorage> qw = new QueryWrapper<>();
        if(!StringUtils.isEmpty(key)){
            qw.like("`key`",key);
        }
        if(!StringUtils.isEmpty(name)){
            qw.like("name",name);
        }

        if(!StringUtils.isEmpty(sort)&&!StringUtils.isEmpty(order)){
            if(order.equalsIgnoreCase("desc")){
                qw.orderByDesc(sort);
            }else {
                qw.orderByAsc(sort);
            }

        }
        storageMapper.selectPage(iPage,qw);
        return iPage;
    }



    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Override
    public DtsStorage add(byte[] bytes,String newName,String filename,int size,String type) throws Exception {
        String url = AliyunOSSUtil.uploadImage(endpoint, accessKeyId, accessKeySecret, bucketName, newName, bytes);

        DtsStorage storage = new DtsStorage();
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setDeleted(false);
        storage.setUrl(url);
        storage.setSize(size);
        storage.setKey(newName);
        storage.setName(filename);
        storage.setType(type);

        storageMapper.insert(storage);

        return storage;

    }

    @Override
    public DtsStorage update(DtsStorage storage) {
        storage.setName(storage.getName());
        storageMapper.updateById(storage);
        return storage;
    }

    @Override
    public DtsStorage delete(DtsStorage storage) {
        storageMapper.deleteById(storage);
        String key = storage.getKey();
        AliyunOSSUtil.deleteFile(endpoint,accessKeyId,accessKeySecret,bucketName,key);


        return storage;
    }
}
